#pragma once
#include "tools.hpp"
#include "logger.hpp"
#include <random>
#include <fstream>
#include <sstream>
#include <atomic>
#include <iostream>
#include <cstdio>
#include <string>

namespace zhiang {
// 生成一个唯一的uid
std::string generate_uid() {
    std::string buid = tools::getMotherboardUUID().substr(0, 8);
    std::random_device rd; // 实例化设备随机数对象
    std::mt19937 generator(rd());// 实例化伪随机数种子
    std::uniform_int_distribution<long long> distribution(0, tools::Umax); // 限定范围
    std::stringstream ss;
    for(int i = 0; i < 2; i++) {
        if(i == 1) ss << "-";
        ss << tools::to62s(distribution(generator));
    }
    ss << '-';
    static std::atomic<unsigned short> idx(0);
    short tmp = idx.fetch_add(1);
    ss << std::setw(4) << std::setfill('0') << std::hex << tmp;
    return buid + "-" + ss.str(); 
}

std::string generate_code() {
    // 被制裁了
    return "8888";
    // -----------------------------------------------------------------
    std::random_device rd; // 实例化设备随机数对象
    std::mt19937 generator(rd());// 实例化伪随机数种子
    std::uniform_int_distribution<long long> distribution(0, 9); // 限定范围
    std::stringstream ss;
    for(int i = 0; i < 4; i++) {
        ss << distribution(generator);
    }
    return ss.str();
}

bool readFile(const std::string& fileName, std::string& body) {
    std::ifstream ifs(fileName, std::ios::binary | std::ios::in);
    if(ifs.is_open() == false) {
        LOG_ERROR("打开文件{}失败！", fileName);
        return false;
    }
    ifs.seekg(0, std::ios::end);
    size_t flen = ifs.tellg();
    ifs.seekg(0, std::ios::beg);
    body.resize(flen);
    ifs.read(&body[0], flen);
    if(ifs.good() == false) {
        LOG_ERROR("读取文件{}失败", fileName);
        ifs.close();
        return false;
    }
    ifs.close();
    return true;
}

bool writeFile(const std::string& fileName, const std::string& body) {
    std::ofstream ofs(fileName, std::ios::binary | std::ios::out | std::ios::trunc);
    if(ofs.is_open() == false) {
        LOG_ERROR("打开文件{}失败！", fileName);
        return false;
    }
    // ofs.write(body.c_str(), body.size());
    ofs << body;
    if(ofs.good() == false) {
        LOG_ERROR("写文件{}失败", fileName);
        ofs.close();
        return false;
    }
    ofs.close();
    return true;
}

bool deleteFile(const std::string& fileName) {
    // 使用C标准库函数remove删除文件
    if (remove(fileName.c_str()) == 0) {
        return true;  // 删除成功
    } else {
        return false; // 删除失败
    }
}

// 检查文件扩展名是否合法
bool isValidExtension(const std::string& filename, const std::string& ex) {
    std::string extension = filename.substr(filename.find_last_of("."));
    return extension == ex;
}

// 保存上传的文件
bool saveUploadedFile(const httplib::MultipartFormData& file, const std::string& fileId, 
                     const std::string& directory, std::string& savedFilePath) {
    try {
        // 创建存储目录
        if (!std::filesystem::exists(directory)) {
            std::filesystem::create_directories(directory);
        }
        
        // 获取文件扩展名
        std::string extension = ".dat"; // 默认扩展名
        size_t dotPos = file.filename.find_last_of(".");
        if (dotPos != std::string::npos) {
            extension = file.filename.substr(dotPos);
        }
        
        // 生成保存的文件路径
        savedFilePath = directory + "/" + fileId + extension;
        
        // 保存文件
        std::ofstream ofs(savedFilePath, std::ios::binary);
        if (!ofs) {
            std::cerr << "无法创建文件: " << savedFilePath << std::endl;
            return false;
        }
        
        ofs.write(file.content.data(), file.content.size());
        ofs.close();
        
        std::cout << "文件保存成功: " << savedFilePath << std::endl;
        return true;
        
    } catch (const std::exception& e) {
        std::cerr << "保存文件时出错: " << e.what() << std::endl;
        return false;
    }
}

}